#include <iostream>
#include <string>
#include <unistd.h>
#include "Thread.hpp"
#include "lockGuard.hpp"

using namespace std;


//临界资源
int tickets = 1000;                                // 全局变量，共享对象
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 静态锁，自动销毁


void threadRoutine(void *args)
{
    std::string message = static_cast<const char *>(args);
    while (true)
    {
        // pthread_mutex_lock(&mutex); // 加锁，是一个让不让你通过的策略
        {//锁的作用域就是临界区
            LockGuard lockguard(&mutex); // RAII 风格的锁,自动维护
            if (tickets > 0)
            {
                usleep(2000);
                cout << message << " get a ticket: " << tickets-- << endl; // 临界区
            }
            else
            {
                break;
            }
        }
    }
    
}

int main()
{
    Thread t1(1, threadRoutine, (void *)"hello1");
    Thread t2(2, threadRoutine, (void *)"hello2");
    Thread t3(3, threadRoutine, (void *)"hello3");
    Thread t4(4, threadRoutine, (void *)"hello4");

    t1.run();
    t2.run();
    t3.run();
    t4.run();

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    
    return 0;
}